package com.foogui.java8.stream;

import com.foogui.java8.enums.Type;
import com.foogui.java8.utils.ListUtil;
import com.foogui.java8.vo.Dish;
import org.junit.Test;

import java.util.*;

import static java.util.stream.Collectors.*;

public class CollectDemo {
    @Test
    public void TestGroupBy(){
        List<Dish> menu = ListUtil.createDishList();

        Map<Type, List<Dish>> collect = menu.stream().collect(groupingBy(Dish::getType));
        //System.out.println(collect);
        Map<Type, List<String>> collect1 = menu.stream().collect(groupingBy(Dish::getType, mapping(Dish::getName, toList())));
        //System.out.println(collect1);
        // 多级分组
        Map<Type, Map<String, List<Integer>>> collect2 = menu.stream()
                .collect(groupingBy(Dish::getType, groupingBy(Dish::getName, mapping(Dish::getCalories, toList()))));
        System.out.println(collect2);
    }
    @Test
    public void TestMaxBy(){
        List<Dish> menu = ListUtil.createDishList();
        Optional<Dish> collect = menu.stream().collect(maxBy(Comparator.comparing(Dish::getType)));
        System.out.println(collect);
    }
    @Test
    public void TestSummingInt(){
        List<Dish> menu = ListUtil.createDishList();
        int collect = menu.stream().collect(summingInt(Dish::getCalories));
        System.out.println(collect);
    }
    @Test
    public void TestJoining(){
        List<Dish> menu = ListUtil.createDishList();
        String collect = menu.stream().map(Dish::getName).collect(joining(","));
        System.out.println(collect);
    }

    @Test
    public void removeDuplicate() {
        HashMap<String, String> map = new HashMap<>();
        map.put("a", "1");
        map.put("8", "4");
        map.put("b", "2");
        Map<String, String> newMap = map.entrySet().stream().collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (key1, key2) -> key1));
        System.out.println(newMap);
    //    排序
        Map<String, String> newMap2 = map.entrySet().stream().sorted(Map.Entry.comparingByValue()).collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
        System.out.println(newMap2);

    }
}
